package com.dream.jump.file

import android.content.Context
import android.os.FileUtils
import com.google.gson.Gson
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import javax.inject.Inject


@Module
@InstallIn(SingletonComponent::class)
class FileConfig @Inject constructor(@ApplicationContext private val context: Context) {
    companion object {
        const val FOLDER_ROOT = "dream"
        const val FOLDER_CONFIG = "config"
        const val FOLDER_IMAGES = "images"
        const val FILE_SYSTEM = "system.json"
    }

    fun createFile() {
        var result = true
        val rootDir = context.getExternalFilesDir(FOLDER_ROOT)!!
        if (!rootDir.exists()) {
            result = rootDir.mkdirs()
        }
        val configDir = File(rootDir, FOLDER_CONFIG)
        if (!configDir.exists()) {
            result = configDir.mkdirs()
        }
        val imageDir = File(rootDir, FOLDER_IMAGES)
        if (!imageDir.exists()) {
            result = imageDir.mkdirs()
        }
        val systemFile = File(configDir, FILE_SYSTEM)
        if (!systemFile.exists()) {
            val assets = context.applicationContext.assets
            assets.open("config/system.json").use { fis ->
                FileOutputStream(systemFile).use { fos ->
                    FileUtils.copy(fis, fos)
                    fos.close()
                    fis.close()
                }
            }
        }
        print(result)
    }

    fun readSystemJson(): SystemConfig {
        val systemFile =
            context.getExternalFilesDir("${FOLDER_ROOT}/${FOLDER_CONFIG}/${FILE_SYSTEM}")!!
        val textJson = FileInputStream(systemFile).bufferedReader().use { it.readText() }
        print(textJson)
        val gson = Gson()
        return gson.fromJson(textJson, SystemConfig::class.java)
    }

}